import { Component, Graphics, Layers, Node, Quat, Vec3, math, v3 } from 'cc';
import { Animatable } from './Animatable';

export class SpaceshipDeathView extends Component implements Animatable {
    private _shape1: Node;

    private _shape2: Node;

    private _vel1x: number;

    private _vel1y: number;

    private _vel2x: number;

    private _vel2y: number;

    private _rot1: number;

    private _rot2: number;

    private _tmp = v3();
    
    protected onLoad(): void {
        this.node.layer = Layers.Enum.UI_2D;
        this._shape1 = new Node();
        this._shape1.layer = Layers.Enum.UI_2D;
        let g = this._shape1.addComponent(Graphics);
        g.fillColor.fromHEX('#ffffff');
        g.moveTo(10, 0);
        g.lineTo(-7, 7);
        g.lineTo(-4, 0);
        g.lineTo(10, 0);
        g.stroke();
        g.fill();
        this.node.addChild(this._shape1);

        this._shape2 = new Node();
        this._shape2.layer = Layers.Enum.UI_2D;
        g = this._shape2.addComponent(Graphics);
        g.fillColor.fromHEX('#ffffff');
        g.moveTo(10, 0);
        g.lineTo(-7, -7);
        g.lineTo(-4, 0);
        g.lineTo(10, 0);
        g.stroke();
        g.fill();
        this.node.addChild(this._shape2);

        this._vel1x = Math.random() * 10 - 5;
        this._vel1y = Math.random() * 10 + 10;
        this._vel2x = Math.random() * 10 - 5;
        this._vel2y = Math.random() * -10 - 10;
        this._rot1 = Math.random() * 3 - 1.5;
        this._rot2 = Math.random() * 3 - 1.5;
    }

    protected onEnable(): void {
        this._shape1.setPosition(Vec3.ZERO);
        this._shape1.setRotation(Quat.IDENTITY);
        this._shape2.setPosition(Vec3.ZERO);
        this._shape2.setRotation(Quat.IDENTITY);
    }

    public animate(time: number): void {
        const { _shape1: shape1, _shape2: shape2 } = this;
        if (shape1 == null || shape2 == null) return;
        shape1.setPosition(this._tmp.set(shape1.position.x + this._vel1x * time, shape1.position.y + this._vel1y * time));
        shape1.setRotationFromEuler(this._tmp.set(0, 0, shape1.eulerAngles.z + math.toDegree(this._rot1 * time)));
        shape2.setPosition(this._tmp.set(shape2.position.x + this._vel2x * time, shape2.position.y + this._vel2y * time));
        shape2.setRotationFromEuler(this._tmp.set(0, 0, shape2.eulerAngles.z + math.toDegree(this._rot2 * time)));
    }
}
